/*
 * PvpPkBuffPositionResource.cpp
 *
 *  Created on: 2014. 6. 16.
 *      Author: the2
 */



#include "PvpPkBuffPositionResource.h"
#include <Database/Static.h>
#include "../NUtil/Pool.h"

namespace ProjectZ { namespace NResource {

PvpPkBuffPositionResource::PvpPkBuffPositionResource()
{

}

PvpPkBuffPositionResource::~PvpPkBuffPositionResource()
{
	Clear();
}


bool
PvpPkBuffPositionResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery(" SELECT * FROM resource_pvp_pk_buff_position");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		PvpPkBuffPositionResource::Flyweight * pFly = new PvpPkBuffPositionResource::Flyweight;

		int index = 0;
		clsAuto->GetRecord() >> NATIONAL_CODE >> index
				>> pFly->_PVP_X >> pFly->_PVP_Y
				>> pFly->_PK_X >> pFly->_PK_Y;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[index] = pFly;
	}

	return true;
}

PvpPkBuffPositionResource::Flyweight *
PvpPkBuffPositionResource::GetFly(int index)
{
	auto iter = clsFlyTree.find(index);

	if ( iter == clsFlyTree.end() )
		return NULL;
	else
		return iter->second;
}

int
PvpPkBuffPositionResource::GetRandomFlyIndex()
{
	auto iter = clsFlyTree.begin();

	std::advance(iter, rand() % clsFlyTree.size());

	if ( iter == clsFlyTree.end() )
		return -1;
	else
		return iter->first;
}

void
PvpPkBuffPositionResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
	clsFlyTree.clear();
}

} /* namespace NResource */ } /* namespace ProjectZ */
